<template>
  <el-main >
    <el-card class="ep-card ep-search">
          <el-row :gutter="0">
              <el-col :span="3" style="float:right">
              <el-button type="primary"  @click="back">返回</el-button>
              </el-col>
          </el-row>
   </el-card>
    <el-tabs :tab-position="tabPosition"  >
      <el-tab-pane label="项目信息">
        <slot name="main"></slot>
      </el-tab-pane>
      <el-tab-pane label="任务处理">
        <el-card  class="box-card" style="margin-top: 20px">
          <div slot="header" class="clearfix" style=" font-size: 14px;">
            <span>审批意见列表</span>
          </div>
          <el-row style="margin-top: 10px;">
            <el-table
              :data="showOpinionList"
              border
              style="width: 100%">
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="50">
              </el-table-column>
              <el-table-column
                prop="nodeName"
                align="center"
                width="180"
                label="任务名称">
              </el-table-column>
              <el-table-column
                prop="createUserName"
                align="center"
                width="180"
                label="处理人">
              </el-table-column>
              <el-table-column
                prop="content"
                align="center"
                width="280"
                label="意见">
              </el-table-column>
              <el-table-column
                prop="createTime"
                align="center"
                width="180"
                label="处理时间"  type="date" :formatter="dateFormatter">
              </el-table-column>
              <el-table-column
                prop="name"
                align="center"
                label="操作"
                width="180">
                <template slot-scope="scope">
                  <el-button type="text"  @click="viewOpinion(scope.row)">查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </el-card>
        
        <el-card class="box-card" style="margin-top: 20px;">
          <div slot="header" class="clearfix" style=" font-size: 14px;">
            <span>项目意见</span>
          </div>
          
          <el-form :model="flowCheck" ref="myOpinion"  >
            <el-row>
            <el-form-item label="融资用途分析"  label-width="140px">
              <el-input type="textarea"
                        :rows="2" v-model="flowCheck.financingpurposes" 
                        autocomplete="off"  ></el-input>
            </el-form-item>
            </el-row>
            <el-row>
            <el-form-item label="第一还款来源分析"  label-width="140px">
              <el-input type="textarea"
                        :rows="2" v-model="flowCheck.firstRepaySource" 
                        autocomplete="off"  ></el-input>
            </el-form-item>
            </el-row>
            <el-row>
            <el-form-item label="第二还款来源分析"  label-width="140px">
              <el-input type="textarea"
                        :rows="2" v-model="flowCheck.secondRepaySource" 
                        autocomplete="off"  ></el-input>
            </el-form-item>
            </el-row>
            <el-row>
            <el-form-item label="风险分析"  label-width="140px">
              <el-input type="textarea"
                        :rows="2" v-model="flowCheck.risk" 
                        autocomplete="off"  ></el-input>
            </el-form-item>
            </el-row>
            <el-row>
            <el-form-item label="审核意见"  label-width="140px">
              <el-input type="textarea"
                        :rows="2" v-model="flowCheck.content" placeholder="请输入审核意见"
                        autocomplete="off"  ></el-input>
            </el-form-item>
            </el-row>
          <el-row>
             
            <el-form-item label="我的结论"  label-width="140px" v-if="showConclusion" required>
              <el-select v-model="taskConclusion" placeholder="请选择">
                <el-option
                  v-for="item in conclusionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-row>    
                  <div style="text-align:center;width:100%;">
                    <el-button type="primary" @click="doSave()">保存</el-button>
                    <el-button type="success" @click="doSubmit()">提交</el-button>
                  </div>

            <!-- </el-form-item> -->
          </el-form>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="流程进展">
        <el-card  class="box-card" style="margin-top: 20px">
          <div slot="header" class="clearfix" style=" font-size: 14px;">
            <span>审批进展</span>
            <el-button style="float:right;margin-left:10px;" type="primary" @click="progress()">图形化进展</el-button>
            <el-button style="float:right;" type="primary" v-show="showParentProgress" @click="parentProgress()">主流程进展</el-button>
          </div>
          <el-row style="margin-top: 10px;">
            <el-table
              :data="tableData"
              border
              style="width: 100%">
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="50">
              </el-table-column>
              <el-table-column
                prop="taskName"
                align="center"
                width="180"
                label="任务名称">
              </el-table-column>
              <el-table-column
                prop="attendUserName"
                align="center"
                width="180"
                label="处理人">
              </el-table-column>
              <el-table-column
                prop="startDate"
                align="center"
                width="180"
                label="任务开始时间"  type="date" :formatter="dateFormatter">
              </el-table-column>
              <el-table-column
                prop="endDate"
                align="center"
                width="180"
                label="任务完成时间"  type="date" :formatter="dateFormatter">
              </el-table-column>
              <el-table-column
                prop="taskConclusion"
                align="center"
                width="180"
                label="结论">
              </el-table-column>
              <el-table-column
                prop="name"
                align="center"
                label="操作"
                width="180">
                <template slot-scope="scope">
                  <el-button type="text" :disabled="scope.row.isAuto == 1 || scope.row.state != 'O'" @click="doManual(scope.row)">手动</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              v-show="tableData.length > 0"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pager.page"
              background
              :page-sizes="[20, 40, 60, 80]"
              :page-size="pager.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pager.total">
            </el-pagination>
          </el-row>
        </el-card>
        <el-dialog :fullscreen="fullscreen" title="图形化进展" style="z-index:9999999999" :visible.sync="designerVisible" :before-close="handleDesignerClose">
            <div slot="title" class="header-title" style="margin-top: -13px">
                <span class="title-name" style="">图形化进展</span>
            </div>
            <iframe ref="ifrm" class="iframe" :src="designerUrl"></iframe>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </el-main>
</template>
<script>
import UserSelector from "./UserSelector";
export default {
  name: "Approval",
  components: {
    UserSelector
  },
  data() {
    return {
      ids: [],
      projectId:'',
      mainStyle: "height:" + (window.innerHeight - 82) + "px",
      cardStyle:
        "height:" + (window.innerHeight - 240) + "px" + ";margin-top: 20px",
      tabPosition: "right",
      tableData: [],
      showOpinionList: [],
      pager: {
        page: 0,
        size: 20,
        total: 0
      },
      dialogFormVisible: false,
      viewHide: true,
      editCode: false,
      showOpinion: {
        createUserName: "",
        taskName: "",
        content: "",
        createDate: ""
      },
      flowCheck:{
        content:"",
        financingpurposes:"",
        firstRepaySource:"",
        secondRepaySource:"",
        risk:"",
        projId:""
      },
      myOpinion: {
        id: "",
        workflowInstanceId: "",
        taskTemplateId: "",
        taskWorkitemId: "",
        content: "",
        createUser: "",
        createUserName: "",
        createOrganName: "",
        createDate: "",
        modifyDate: "",
        modifyUser: "",
        taskName: ""
      },
      taskWorkitem: {},
      taskTemplate: {},
      workflowInstance: {},
      taskConclusion: "",
      dialogTitle: "审批",
      entityId: "",
      conclusionOptions: [
        { label: "通过", value: "通过" },
        { label: "不通过", value: "不通过" },
        { label: "退回", value: "退回" }
      ],
      workflowInstanceId: "",
      showConclusion: false,
      addSign: false,
      sign: "0",
      signUser: "",
      isCc: false,
      cc: "0",
      ccUser: "",
      isManual: true,
      designerVisible: false,
      designerUrl: "",
      fullscreen: true,
      showParentProgress: false,
      users: [],
      user:{}
      
    };
  },
  computed: {
    /*        height() {
                  return `calc(100vh - 350px)`;
              }*/
  },
  mounted() {
    this.getBusinessInfo();
    this.getusers();
    this.user=JSON.parse(sessionStorage.getItem("user"));
  },
  methods: {
    back(){
        this.$router.push({path:"/mywork/taskLog"});
      },
    getprojectId(){
      return this.projectId;
    },
    getusers() {
      let params = {};
      this.$api
        .formPost(  "/api/auth/sysuser/doGetList", params)
        .then(res => {
          if (res.retHead.code == "0000000") {
            this.users = res.retBody.list;
          }
        });
    },
    
    //保存风险经理意见
      doSave(){
        
          //保存意见到本地
              this.$api
                .formPost("/api/biz/flowCheck/doSave",
                  this.flowCheck
                )
                .then(res => {
                  if (res.retHead.code == "0000000") {
                      this.$message({
                        type: "success",
                        message: "保存成功!"
                      });
                      this.getBusinessInfo();
                  }
                });
      },
      //提交
      doSubmit(){
        let params = {};
        params.taskWorkitemId=this.taskWorkitem.id;
        params.isSubmit = "1";
        params.userId =this.user.id;
        let conent="1";
        if (this.taskConclusion != null) {
            params.taskConclusion = this.taskConclusion;
            if (this.taskConclusion === "不通过") {
              conent="2";
            }
            if(this.taskConclusion === "退回"){
              conent="3";
            }
        }
        params.variables = {
          jl:conent
        };
         this.$api.post("/wf/submit", params).then(res => {
            if (res.status === "0") {
              this.$message({
                type: "success",
                message: "提交成功!"
              });
            
              if (params.isSubmit) {
                this.$router.push({
                  path: "/mywork/taskLog"
                });
              } else {
                this.getBusinessInfo();
              }
            }else{
              this.$message({
                type: "success",
                message: res.message
              });
            }
          }); 
      },

    // 获取业务信息
    getBusinessInfo: function() {
       let user=JSON.parse(sessionStorage.getItem("user"));
      
      this.$api
        .post("/wf/common/approval?id=" + this.$route.query.id)
        .then(res => {
          if (res.status === "0") {
            if(res.data != null){
              this.projectId = res.data.businessRelation.mid;
              //获取审批意见列表
              this.$api
                .formPost("/api/biz/flowCheck/doGetList", {
                  pageNum: 1,
                  pageSize: 9999,
                  projId: this.projectId
                })
                .then(res => {
                  if (res.retHead.code == "0000000" && res.retBody != null) {
                    console.log("测试3");
                    console.log(res.retBody);
                    this.showOpinionList = res.retBody.list;
                  }
                });
              this.flowCheck.projId = this.projectId;
              this.flowCheck.nodeCode = res.data.taskWorkitem.taskCode; //节点编号
              this.flowCheck.nodeName = res.data.taskWorkitem.taskName; //节点名称
              //获取当前节点审批意见
              this.$api
                .formPost("/api/biz/flowCheck/doGetByNodeCodeAndProjId",
                  {
                    projId: this.projectId,
                    nodeCode: res.data.taskWorkitem.taskCode
                  }
                )
                .then(res => {
                  if (res.retHead.code == "0000000") {
                    if (res.retBody != null) {
                      console.log("测试1");
                      this.flowCheck = res.retBody;
                      this.flowCheck.createTime = new Date(
                        res.retBody.createTime
                      );
                      if (res.retBody.updateTime) {
                        this.flowCheck.updateTime = new Date(
                          res.retBody.updateTime
                        );
                      }
                    } else {
                      console.log("测试2");

                      this.flowCheck.content = ""; //审批意见
                      this.flowCheck.createUserId = this.user.id;
                      this.flowCheck.createUserName = this.user.realName;
                      console.log(this.flowCheck);
                    }
                  }
                });
            }
           // this.showOpinionList = res.data.showOpinionList;
            //this.myOpinion = res.data.myOpinion;
            let opinion = res.data.myOpinion;

            if (opinion != null && typeof opinion !== "undefined") {
              this.myOpinion = {
                id: opinion.id || "",
                workflowInstanceId: opinion.workflowInstanceId || "",
                taskTemplateId: opinion.taskTemplateId || "",
                taskWorkitemId: opinion.taskWorkitemId || "",
                content: opinion.content || "",
                createUser: opinion.createUser || "",
                createUserName: opinion.createUserName || "",
                createOrganName: opinion.createOrganName || "",
                createDate: opinion.createDate || "",
                modifyDate: opinion.modifyDate || "",
                modifyUser: opinion.modifyUser || "",
                taskName: opinion.taskName || ""
              };
            } else {
              this.myOpinion.id = "";
              this.myOpinion.workflowInstanceId =
                res.data.taskWorkitem.workflowInstanceId;
              this.myOpinion.taskTemplateId =
                res.data.taskWorkitem.taskTemplateId;
              this.myOpinion.taskWorkitemId = res.data.taskWorkitem.id;
              //content从前端接受
              this.myOpinion.createUser = user.id;
              this.myOpinion.createUserName = user.realName;
              this.myOpinion.createOrganName = "";
              this.myOpinion.createDate = new Date();
              this.myOpinion.modifyDate = new Date();
              this.myOpinion.modifyUser = user.id;
              this.myOpinion.taskName = res.data.taskWorkitem.taskName;
            }

            if (res.data.taskWorkitem != null) {
              this.taskWorkitem = res.data.taskWorkitem;
              if (this.taskWorkitem.isSub != "0") {
                this.showParentProgress = true;
              }
              this.getTaskWorkitemList(this.taskWorkitem.workflowInstanceId);

              if (this.taskWorkitem.taskConclusion != null) {
                this.taskConclusion = this.taskWorkitem.taskConclusion || "";
              }
            }

            if (res.data.workflowInstance != null) {
              this.workflowInstance = res.data.workflowInstance;
            }

            if (res.data.taskTemplate != null) {
              this.taskTemplate = res.data.taskTemplate;
              if (
                this.taskTemplate.isReturn != null &&
                this.taskTemplate.isReturn == "1"
              ) {
                this.showConclusion = true;
              }
              if (
                this.taskTemplate.addSign != null &&
                this.taskTemplate.addSign == "1"
              ) {
                this.addSign = true;
              }
              if (
                this.taskTemplate.isCc != null &&
                this.taskTemplate.isCc == "1"
              ) {
                this.isCc = true;
              }
              if (
                this.taskTemplate.isManual != null &&
                this.taskTemplate.isManual !== "1"
              ) {
                this.isManual = false;
              }
            }
          }
        });
    },
    // 获取任务明细列表
    getTaskWorkitemList: function(workflowInstanceId) {
      let params = {
        page: this.pager.page === 0 ? this.pager.page : this.pager.page - 1,
        size: this.pager.size,
        workflowInstanceId: workflowInstanceId || ""
      };
      this.$api.post("/wf/taskWorkitem/progress", params).then(res => {
        if (res.status === "0") {
          this.tableData = res.data.resContent;
          this.pager.total = res.data.total;
        }
      });
    },
    dateFormatter: function(row, column) {
      let datetime = row[column.property];
      if (datetime) {
        datetime = new Date(datetime);
        let y = datetime.getFullYear() + "-";
        let mon = datetime.getMonth() + 1 + "-";
        let d = datetime.getDate();
        return y + mon + d;
      }
      return "";
    },
    doManual: function(item) {
      if (this.isManual) {
        this.$api.post("/wf/taskWorkitem/manual/" + item.id).then(res => {
          if (res.status === "0") {
            this.$message({
              type: "success",
              message: "执行成功!"
            });
            this.getTaskWorkitemList(this.taskWorkitem.workflowInstanceId);
          } else {
            this.$message({
              type: "error",
              message: "执行失败!"
            });
          }
        });
      } else {
        this.$message({
          type: "error",
          message: "该任务不允许手动执行!"
        });
      }
    },
    viewOpinion: function(item) {
      this.dialogFormVisible = true;
      //console.log(item);
      this.showOpinion = item;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pager.size = val;
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pager.page = val;
    },
    selectCcUser(data) {
      let uid = [];
      if (data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          uid.push(data[i].value);
        }
      }
      if (uid.length > 0) {
        this.ccUser = uid.join(",");
      }
    },
    selectSignUser(data) {
      if (data.length > 0) {
        this.signUser = data[0].value;
      }
    },
    progress: function() {
      let curWwwPath = window.location.href;
      let pos = curWwwPath.indexOf("#" + this.$route.path);
      let localhostPath = curWwwPath.substring(0, pos);
      this.designerUrl =
        localhostPath +
        "static/gui/instance.html?id=" +
        this.taskWorkitem.workflowInstanceId +
        "&baseURL=" +
        encodeURIComponent( this.baseURL)+"&token="+encodeURIComponent(sessionStorage.getItem("token")||'');
      this.designerVisible = true;
    },
    parentProgress: function() {
      let curWwwPath = window.location.href;
      let pos = curWwwPath.indexOf("#" + this.$route.path);
      let localhostPath = curWwwPath.substring(0, pos);
      if (
        this.workflowInstance != null &&
        this.workflowInstance.parentWorflowInstanceId != null
      ) {
        this.designerUrl =
          localhostPath +
          "static/gui/instance.html?id=" +
          this.workflowInstance.parentWorflowInstanceId +
          "&baseURL=" +
          encodeURIComponent(this.baseURL)+"&token="+encodeURIComponent(sessionStorage.getItem("token")||'');
      }
      this.designerVisible = true;
    },
    handleDesignerClose: function() {
      this.designerVisible = false;
    }
  }
};
</script>
<style  scoped>
.el-main {
  padding: 0;
  overflow: hidden;
  background-color: #f5f5f5;
}

.iframe {
  width: 100%;
  height: 100%;
  border: 0;
  overflow: hidden;
  box-sizing: border-box;
  position: absolute;
  bottom: 0;
  left: 0;
  top: 54px;
}
.title-name {
  font-size: 24px;
}
</style>
